<template>
  <van-form @submit="onSubmit">
    <van-cell-group inset>
      <van-field
          v-model="phone"
          left-icon="phone"
          name="phone"
          label="手机号"
          placeholder="请填写手机号"
          type="tel"
          size="large"
          clearable
      />
      <van-field
          v-model="password"
          center
          left-icon="setting"
          name="password"
          label="密码"
          placeholder="请填写密码"
          size="large"
          style="margin-top: 2vh"
          clearable
      >
      </van-field>
    </van-cell-group>


    <div style="margin-top: 10vh;">
      <van-button round block type="primary" native-type="submit">
        登录
      </van-button>
    </div>
  </van-form>

</template>


<script setup>
import { ref} from "vue";
import {showToast} from "vant";
import {loginUserByAccount} from "../../api/user/user.js";
import {useUserStore} from "../../stores/user.js";
import {useRouter} from "vue-router";
const router = useRouter();
const phone = ref('');
const password = ref('');
const userStoreAPI = useUserStore();
import { useTabbarStore } from '../../stores/tabbar';
const tabbarStore = useTabbarStore();

const onSubmit = async () => {
  //校验参数
  //手机号的正则校验
  if (phone.value == ''){
    showToast("请填写手机号");
    return;
  }
  if (phone.value.length != 11){
    showToast("手机号不正确");
    return;
  }
  const phoneReg = /^1[3-9]\d{9}$/;
  if (!phoneReg.test(phone.value)){
    showToast("手机号不正确");
    return;
  }


  if (password.value == ''){
    showToast("请填写验证码");
    return;
  }

  const userLoginRequest = {
    phone: phone.value,
    password: password.value
  };

  //调用登录接口
  const res = await loginUserByAccount(userLoginRequest);
  if(res.success){
    showToast("登录成功");
    const userInfo = res.data;
    //保存用户信息到本地
    // localStorage.setItem("userInfo", JSON.stringify(userInfo));

    userStoreAPI.setLoginInfo(userInfo,'');
    //跳转到首页
    tabbarStore.setActive('home');
    router.push("/");
  }else{
  }
};




</script>



<style scoped>

</style>